package com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;

import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

public class Bank implements Serializable {
	private static final long serialVersionUID = -2840885510330537029L;
	
	static final String MES_REACH_MAX_CLIENT_COUNT = "Number of clients reaches max value";
	static final String MES_CLIENT_EXIST = "Client with given name already exists";
	
	static final int MAX_CLIENT_COUNT = 20;
	static final int MAX_LISTENER_COUNT = 10;
	
	private Client[] clients;
	private int clientCount;
	
	private ClientRegistrationListener[] listeners;
	private int listenerCount;
	
	public class PrintClientListener implements ClientRegistrationListener {
		private static final long serialVersionUID = -9001445264960729318L;

		public void onClientAdded(Client c) {
			System.out.println("Client <" + c.getClientSalutation() + "> added");
		}
	}
	
	public class EmailNotificationListener implements ClientRegistrationListener {
		private static final long serialVersionUID = -3003678824271368525L;

		public void onClientAdded(Client c) {
			System.out.println("Notification email for client <" + c.getClientSalutation() + "> to be sent");
		}
	}
	
	public Bank() {
		clients = new Client[MAX_CLIENT_COUNT];
		clientCount = 0;
		
		listeners = new ClientRegistrationListener[MAX_LISTENER_COUNT];
		listenerCount = 0;
		
		// DebugListener
		addListener( new ClientRegistrationListener() {
			private static final long serialVersionUID = -1284050215137377340L;

			public void onClientAdded(Client c) {
				System.out.println(new Date().toString() + ": Client<" + c.getClientSalutation() + "> added");
			}
		});
	}
		
	public Client[] getClients() {
		return Arrays.copyOf(clients, clientCount);
	}
	
	public void addClient(Client client) throws ArrayIndexOutOfBoundsException, ClientExistsException {
		if (clientCount >= MAX_CLIENT_COUNT)
			throw new ArrayIndexOutOfBoundsException(MES_REACH_MAX_CLIENT_COUNT);
		
		if (checkClientExist(client)) {
			throw new ClientExistsException(MES_CLIENT_EXIST, client.getClientSalutation());
		}
		
		clients[clientCount++] = client;
		
		for (int i = 0; i < listenerCount; i++) {
			listeners[i].onClientAdded(client);
		}
	}
	
	private boolean checkClientExist(Client client) {
		boolean exist = false;
		
		for (int i=0; i<clientCount; i++)
			if (this.clients[i].getClientSalutation().equals(client.getClientSalutation())) {				
				exist = true;
				break;
			}
		
		return exist;
	}

	public void addListener(ClientRegistrationListener listener) {
		if (listenerCount < MAX_LISTENER_COUNT)
			listeners[listenerCount++] = listener;		
	}
}
